/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.invocation.server;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;

import org.nuxeo.gwt.habyt.invocation.client.Invocation;
import org.nuxeo.gwt.habyt.invocation.client.InvocationException;
import org.nuxeo.gwt.habyt.invocation.client.InvocationResponse;
import org.nuxeo.gwt.habyt.invocation.client.ObjectRef;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class ServerInvoker {

    private static ThreadLocal<HttpServletRequest> REQUEST = new ThreadLocal<HttpServletRequest>();

    public static HttpServletRequest getRequest() {
        return REQUEST.get();
    }

    protected InvocationHandlerProvider provider;

    public ServerInvoker(ServletConfig config) throws InvocationException {
        String providerClass = config.getInitParameter("invocation-handler-provider");
        if (providerClass != null) {
            try {
                provider = (InvocationHandlerProvider) Class.forName(
                        providerClass).newInstance();
            } catch (Exception e) {
                throw new InvocationException(
                        "Failed to instantiate invocation handler provider: "
                                + providerClass, e);
            }
        } else {
            provider = new DefaultInvocationHandlerProvider();
        }
        try {
            provider.init(config);
        } catch (Exception e) {
            throw new InvocationException(
                    "Failed to initialize invocation handler provider: "
                            + providerClass, e);
        }
    }

    public InvocationHandlerProvider getInvocationHandlerProvider() {
        return provider;
    }

    public InvocationResponse invoke(HttpServletRequest req,
            Invocation invocation) throws InvocationException {
        ObjectRef target = invocation.getTarget();
        if (target == null) {
            throw new InvocationException(
                    "A client invocation must have a target object");
        }
        String type = target.getType();
        if (type == null) {
            throw new InvocationException("A target object must have a type");
        }
        InvocationHandler handler = provider.getHandler(type);
        if (handler == null) {
            throw new InvocationException(
                    "No registered server handler for the invocation type: "
                            + type);
        }
        try {
            REQUEST.set(req);
            InvocationResponse response = new InvocationResponse(invocation);
            handler.invoke(invocation, response);
            return response;
        } catch (InvocationException e) {
            throw e;
        } catch (Throwable t) {
            // t.printStackTrace();
            throw new InvocationException("Unhandled Exception: "
                    + t.getMessage());
        } finally {
            REQUEST.remove();
        }
    }
}
